package cn.edu.scnu.controller;

import cn.edu.scnu.config.ExcelReportGenerator;
import cn.edu.scnu.config.Result;
import cn.edu.scnu.entity.MovieStats;
import cn.edu.scnu.service.MovieStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * POI报表技术，生成EXCEL报表
 */
@RestController
public class ReportController {

    @Autowired
    private MovieStatsService movieStatsService;

    @GetMapping("/report/movie-stats")
    public ResponseEntity generateMovieStatsReport() {
        List<MovieStats> movieStatsList = movieStatsService.getAllMovieStats();
        try {
            // 创建临时文件
            File tempFile = File.createTempFile("movie-stats-report", ".xlsx");
            ExcelReportGenerator.generateMovieStatsReport(movieStatsList, tempFile.getAbsolutePath());

            // 设置下载的HTTP头部
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=movie-stats-report.xlsx");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            InputStreamResource resource = new InputStreamResource(new FileInputStream(tempFile));
            return ResponseEntity.ok().headers(headers).body(resource);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("报表生成失败: " + e.getMessage()));
        }
    }
}

